package com.wtwd.device.service.impl;


import com.alibaba.fastjson.JSON;
import com.wtwd.device.constant.Constants;
import com.wtwd.device.constant.RespCode;
import com.wtwd.device.exception.BaseException;
import com.wtwd.device.model.entity.SysUser;
import com.wtwd.device.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


/**
 * @author mjy
 * @date 2021/06/08
 * @description
 */
@Service
public class RedisServiceImpl implements RedisService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void createToken(SysUser sysUser, String token) {
        //以token为键，存储该用户key值(key值以前缀+账号名存取(账号名不能重复，保证key值的唯一性))默认过期时间30分钟
        String key = Constants.WEB_TOKEN_PREFIX + sysUser.getUserId();
        setKey(token, key, Constants.TOKEN_EXPIRE, TimeUnit.MINUTES);
        //以key为键,用户信息为value,存储用户信息
        HashMap<String, Object> userMap = new HashMap<>();
        userMap.put("current_token", token);//判断用户是否多端登录
        userMap.put("user", JSON.toJSONString(sysUser));
        setHash(key, userMap, Constants.TOKEN_EXPIRE, TimeUnit.MINUTES);
    }

    @Override
    public void setKey(String key, String value, long expireTime, TimeUnit timeUnit) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        if (expireTime == 0) {
            valueOperations.set(key, value);
        } else {
            valueOperations.set(key, value, expireTime, timeUnit);
        }
    }

    @Override
    public void setHash(String key, Map<String, Object> map, long expireTime, TimeUnit timeUnit) {
        redisTemplate.opsForHash().putAll(key, map);
        if (expireTime != 0) {
            redisTemplate.expire(key, expireTime, timeUnit);
        }
    }

    @Override
    public Map<String, Object> getUserInfoByToken(String token) {
        Map<String, Object> userInfo = null;
        try {
            // 通过token获取到用户对应的token
            String key = (String) redisTemplate.opsForValue().get(token);
            // 通过用户对应的key值，得到对应用户数据
            userInfo = redisTemplate.opsForHash().entries(key);
        } catch (RuntimeException e) {
            throw new BaseException(RespCode.TOKEN_UNAUTHORIZED);
        } finally {
            return userInfo;
        }
    }


    @Override
    public boolean delKey(String key) {
        return redisTemplate.delete(key);
    }

    @Override
    public void bathDelHashKey(String key, List<String> hashKeys) {
        redisTemplate.opsForHash().delete(key, hashKeys.toArray());
    }

    @Override
    public void bathDelKey(List<String> keys) {
        if (keys != null && keys.size() > 0) {
            redisTemplate.delete(keys);
        }
    }

    @Override
    public void saveCache(String key, String hashKey, Object object) {
        Map<String, Object> map = redisTemplate.opsForHash().entries(key);
        if (map == null) {
            map = new HashMap<String, Object>();
        }
        map.put(hashKey, object);
        redisTemplate.opsForHash().putAll(key, map);
    }

    @Override
    public void deleteCache(String key, String hashKey) {
        Map<String, Object> map = redisTemplate.opsForHash().entries(key);
        if (map != null) {
            redisTemplate.opsForHash().delete(key, hashKey);
        }
    }

    @Override
    public Map<String, Object> getHashValue(String key) {
        return redisTemplate.opsForHash().entries(key);
    }


}
